<script setup>
import { ref,watch } from 'vue'
import { getCode, LoginService,RegisterService,changePasswordService } from "@/api/apis.js"

const login_way = ref('passwordLogin')     // 登录'codeLogin''passwordLogin'   和注册'regist'，忘记密码'forgetPass'方式
const phone = ref('')             // 手机号
const code = ref('')              // 验证码
const password= ref('')			 //密码
const confirmPassword= ref('')       //确认密码
const newPassword = ref('')        //新密码
const msg = ref('获取验证码')      // 验证码按钮文本
const isAgreePrivacy = ref(false)      // 协议状态 
let timer;                        // 计时器
const arr_login = ref([{way:'密码登录',key:'passwordLogin'},{way:'验证码登录',key:'codeLogin'}])


//清空表单数据
const resetData = ()=>{
	phone.value=''
	code.value=''
	password.value=''
	msg.value='获取验证码'
	confirmPassword.value=''
	newPassword.value=''
}
//监听状态是否发送变化，变化则清空表单
watch(login_way,()=>{
	resetData()
})

//校验
const Verification = (way)=>{
	if(!phone.value) {
		  return uni.showToast({ title: "请输入手机号", icon: "none" })
	}
	if (!/^1[3-9]\d{9}$/.test(phone.value)) {
	  return uni.showToast({ title: "手机号格式错误", icon: "none" })
	}
	if(!way) return 
	else if (way==='codeLoign') {
		if(!code.value) return uni.showToast({title:'请输入验证码',icon:'none'})
	}
	else if (way==='passwordLogin'){
		if(!password.value) return uni.showToast({title:'请输入密码',icon:'none'})
	}
	else if (way==='regist'){
		if(!code.value) return uni.showToast({title:'请输入验证码',icon:'none'})
		if(!password.value) return uni.showToast({title:'请输入密码',icon:'none'})
		if(!confirmPassword.value) return uni.showToast({title:'请确认密码',icon:'none'})
		if(password.value!==confirmPassword.value) return uni.showToast({title:'前后密码不一致',icon:'none'})
	}
	else if (way==='forgetPass'){
		if(!code.value) return uni.showToast({title:'请输入验证码',icon:'none'})
		if(!newPassword.value) return uni.showToast({title:'请输入新密码',icon:'none'})
		if(!confirmPassword.value) return uni.showToast({title:'请确认新密码',icon:'none'})
		if(confirmPassword.value!==newPassword.value) return uni.showToast({title:'前后密码不一致',icon:'none'})
	}
	
	return 'true'
	
	
}


// 获取验证码
const getVerificationCode = async (way) => {
  //防止重复点击获取验证码
  if(timer) return 
  
  Verification('')
  
  
  
  const res = await getCode({ phone: phone.value,way})
  if (res.data.code === 1) {
    // 倒计时逻辑
    let count = 5
    msg.value = `${count}s`
    timer = setInterval(() => {
      if (--count <= 0) {
        clearInterval(timer)
		timer=null
		
        msg.value = "重新获取"
        return
      }
      msg.value = `${count}s`
    }, 1000)
  }
}



// 登录处理
const handleLogin = async () => {
  if (!isAgreePrivacy.value) {
    return uni.showToast({ title: "请先同意协议", icon: "none" })
  }
  //输入格式不对，结束函数
  const res= Verification(login_way.value)
  if(res!=='true') return 
  //请求参数
  let data 
  if(login_way.value==='passwordLogin')data = {phone: phone.value,password: password.value}
  else data = {phone:phone.value, code:code.value}
  //发送请求
  try {
    const res = await LoginService(data)
	console.log(res)
    if (res.data.code === 1) {
      uni.showToast({ title: "登录成功" })
  		  uni.setStorageSync('token',res.data.data.token)
  		  uni.setStorageSync('username',res.data.data.username)
  		  uni.setStorageSync('id',res.data.data.userId)
     setTimeout(()=>{
  			  uni.switchTab({ url: '/pages/user/user' })
  		 },1000)
    }
  } catch (e) {
    uni.showToast({ title: e.msg || "登录失败", icon: "none" })
  }
}

//注册逻辑
const handleRegister=async()=>{
	if(Verification('regist')!=='true') return 
	try {
		const res=await RegisterService({
			phone:phone.value,
			password:password.value,
			rePassword:confirmPassword.value,
			code:code.value
		})
		if(res.data.code===1){
			uni.showToast({
				icon:'success',
				title:'注册成功'
			})
			setTimeout(()=>{
				login_way.value='passwordLogin'
			},1000)
		} 
	}catch(e){
		uni.showToast({
			icon:'error',
			title:e.msg
		})
		
	}
}


//重置密码
const handleReset=async()=>{
	if(Verification('forgetPass')!=='true') return 
	
	try {
		const res=await changePasswordService({
			phone:phone.value,
			password:newPassword.value,
			rePassword:confirmPassword.value,
			code:code.value
		})
		console.log(res)
		if(res.data.code===1){
			uni.showToast({
				icon:'success',
				title:'操作成功'
			})
			setTimeout(()=>{
				login_way.value='passwordLogin'
			},1000)
		} 
	}catch(e){
		uni.showToast({
			icon:'error',
			title:e.msg
		})
		
	}
	
	
}
//跳转隐私协议界面
const onOpenPrivacyContract = ()=>{
	uni.navigateTo({
		url:'/pages/fast_login/protocal'
	})
}
//返回登录
const toLogin= ()=>{
	login_way.value='passwordLogin'
}
</script>

<template>
  <view class="container">
    <!-- 头部区域 -->
    <view class="header">
      <image class="logo" src="/static/logo.png" />
      <view class="subtitle">时刻守护您的道路安全</view>
    </view>

    <!-- 主功能区域 -->
    <view class="main-card" v-if='login_way.includes("Login")'>
      <!-- 模式切换 -->
      <view class="mode-tabs">
		<text 
		 :key="item.key"
          v-for="item in arr_login" 
          :class="{active: login_way === item.key }"
          @tap="login_way = item.key"
        >{{ item.way }}</text>
		
      </view>

      <!-- 密码登录表单 -->
      <view v-if="login_way === 'passwordLogin'" class="form">
        <view class="input-box">
          <image src="/static/phone.png" class="input-icon"/>
          <input v-model="phone" placeholder="请输入手机号" type="number" />
        </view>
        <view class="input-box">
          <image src="/static/password.png" class="input-icon"/>
          <input v-model="password" password placeholder="请输入密码" />
        </view>
        <text class="forget-pwd" @tap="login_way = 'forgetPass'">忘记密码？</text>
        <button class="submit-btn" @tap="handleLogin">登录</button>
      </view>

      <!-- 验证码登录表单 -->
      <view v-if="login_way === 'codeLogin'" class="form">
        <view class="input-box">
          <image src="/static/phone.png" class="input-icon"/>
          <input v-model="phone" placeholder="请输入手机号" type="number" />
        </view>
        <view class="input-box code-box">
          <image src="/static/password.png" class="input-icon"/>
          <input v-model="code" placeholder="输入验证码" />
          <view class="get-code" @tap="getVerificationCode('code')">{{ msg }}</view>
        </view>
        <button class="submit-btn" @tap="handleLogin">登录</button>
      </view>
	 

      <!-- 注册入口 -->
      <view class="extra-links">
        <text>没有账号？</text>
        <text class="highlight" @tap="login_way = 'regist'">立即注册</text>
      </view>
    </view>

    <!-- 协议声明 -->
   <view class="tips" v-if='login_way.includes("Login")'>
     <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
       <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
       <text>我已阅读并同意</text>
     </label>
     <navigator class="link" hover-class="none" url="./protocal">《服务条款》</navigator>
     和
     <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
   </view>


    <!-- 注册页面 -->
	   <view class="main-card " v-if="login_way === 'regist'">
	      <!-- 标题 -->
	      <view class="title">注册账号</view>
	      <!-- 表单 -->
	      <view class="form">
	        <view class="input-box">
	          <image src="/static/phone.png" class="input-icon"/>
	          <input v-model="phone" placeholder="请输入手机号" type="number" />
	        </view>
	        <view class="input-box code-box">
	          <image src="/static/password.png" class="input-icon"/>
	          <input v-model="code" placeholder="输入验证码" />
	          <view class="get-code" @tap="getVerificationCode('regist')">{{ msg }}</view>
	        </view>
	        <view class="input-box">
	          <image src="/static/password.png" class="input-icon"/>
	          <input v-model="password" password placeholder="请输入密码" />
	        </view>
	        <view class="input-box">
	          <image src="/static/password.png" class="input-icon"/>
	          <input v-model="confirmPassword" password placeholder="确认密码" />
	        </view>
	        <button class="submit-btn" @tap="handleRegister">立即注册</button>
	  
	        <!-- 已有账号 -->
	        <view class="extra-links">
	          <text>已有账号？</text>
	          <text class="highlight" @tap="toLogin">去登录</text>
	        </view>
	      </view>
	    </view>
	
	
	
	
    <!-- 忘记密码页面 -->
   <view class="main-card"  v-if="login_way==='forgetPass'">
       <view class="title">重置密码</view>
       
       <view class="form">
         <view class="input-box">
           <image src="/static/phone.png" class="input-icon"/>
           <input v-model="phone" placeholder="请输入手机号" type="number" />
         </view>
         <view class="input-box code-box">
           <image src="/static/password.png" class="input-icon"/>
           <input v-model="code" placeholder="输入验证码" />
           <view class="get-code" @tap="getVerificationCode('findPassword')">{{ msg }}</view>
         </view>
         <view class="input-box">
           <image src="/static/password.png" class="input-icon"/>
           <input v-model="newPassword" password placeholder="请输入新密码" />
         </view>
         <view class="input-box">
           <image src="/static/password.png" class="input-icon"/>
           <input v-model="confirmPassword" password placeholder="确认新密码" />
         </view>
   
         <button class="submit-btn" @tap="handleReset">立即重置</button>
   
         <view class="extra-links">
           <text>想起密码？</text>
           <text class="highlight" @tap="toLogin">返回登录</text>
         </view>
       </view>
     </view>
  </view>
</template>

<style lang="scss">
.container {
  background: linear-gradient(180deg, #F6FFFD 0%, #E0F5EF 100%);
  min-height: 100vh;
  padding: 60rpx 40rpx;

  .header {
    text-align: center;
    .logo {
      width: 160rpx;
      height: 160rpx;
      margin-bottom: 20rpx;
      border-radius: 24rpx;
      box-shadow: 0 8rpx 20rpx rgba(24, 160, 128, 0.1);
    }
    .title {
      display: block;
      font-size: 44rpx;
      color: #1A7C6C;
      font-weight: 600;
      letter-spacing: 2rpx;
    }
    .subtitle {
      font-size: 26rpx;
      color: #88B8AD;
      letter-spacing: 4rpx;
    }
  }

  .main-card {
    background: #FFF;
    border-radius: 24rpx;
    padding: 50rpx 40rpx;
    margin-top: 80rpx;
    box-shadow: 0 10rpx 40rpx rgba(24, 160, 128, 0.08);
    .title{
		font-weight: 700;
		font-size: 40rpx;
		margin-top: -20rpx;
		margin-bottom: 40rpx;
	}
    .mode-tabs {
      display: flex;
      border-bottom: 2rpx solid #EDF8F5;
      margin-bottom: 60rpx;
      
      text {
        flex: 1;
        text-align: center;
        font-size: 34rpx;
        color: #A5C9C1;
        padding-bottom: 24rpx;
        position: relative;
        
        &.active {
          color: #1A7C6C;
          font-weight: 500;
          
          &::after {
            content: '';
            position: absolute;
            bottom: -2rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 80rpx;
            height: 6rpx;
            background: #1A7C6C;
            border-radius: 3rpx;
          }
        }
      }
    }

    .input-box {
      position: relative;
      margin-bottom: 40rpx;
      background: #F8FFFD;
      border-radius: 12rpx;
      border: 2rpx solid #E5F7F1;
      
      .input-icon {
        position: absolute;
        left: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 40rpx;
        height: 40rpx;
      }
      
      input {
        height: 100rpx;
        padding: 0 30rpx 0 90rpx;
        font-size: 32rpx;
        color: #447E6F;
      }
      
      &.code-box {
        .get-code {
		  z-index: 6;
          position: absolute;
          right: 30rpx;
          top: 50%;
          transform: translateY(-50%);
          color: #1A7C6C;
          font-size: 28rpx;
          
          &[disabled] {
            color: #C1DCD4;
          }
        }
      }
    }

    .forget-pwd {
      display: block;
      text-align: right;
      font-size: 26rpx;
      color: #88B8AD;
      margin: -20rpx 0 40rpx;
    }

    .submit-btn {
      height: 96rpx;
      line-height: 96rpx;
      background: linear-gradient(90deg, #1A9C7C, #21C895);
      color: #FFF;
      font-size: 34rpx;
      border-radius: 48rpx;
      box-shadow: 0 8rpx 24rpx rgba(26, 156, 124, 0.2);
    }

    .extra-links {
      text-align: center;
      margin-top: 50rpx;
      font-size: 28rpx;
      color: #7DA89A;
      
      .highlight {
        color: #1A9C7C;
        margin-left: 16rpx;
        text-decoration: underline;
      }
    }
  }

  .tips {
	position: absolute;
	bottom: 20rpx;
	left: 20rpx;
	right: 20rpx;
	font-size: 22rpx;
	color: #999;
	text-align: center;
	
	.radio {
	  transform: scale(0.6);
	  margin-right: -4rpx;
	  margin-top: -4rpx;
	  vertical-align: middle;
	}
	
	.link {
	  display: inline;
	  color: #28bb9c;
	}
    

  }
}
</style>